import json

from django.http import JsonResponse
from django.views.decorators.http import require_GET, require_http_methods

from userApp.models import Person


@require_GET
def name(request):
    # 获取请求参数
    name = request.GET.get('name', 'default')
    # mock response
    rsp = {'name': name, 'author': 'xxx'}
    # 返回rsp的json格式
    return JsonResponse(rsp)


@require_http_methods(['GET', 'POST'])
def person(request):
    if request.method == 'GET':
        return queryPersons(request)
    else:
        return createPerson(request)


def queryPersons(request):
    # 获取请求参数
    id = request.GET.get('id')
    # mock response
    qs = Person.objects.filter(id=id) if id else Person.objects.all()
    rsp = [q.toDict() for q in qs]
    # 返回rsp的json格式
    return JsonResponse(rsp, safe=False)


def createPerson(request):
    p = json.loads(request.body)
    p = Person(**p)
    p.save()
    # 返回rsp的json格式
    return JsonResponse(p.toDict())
